<?php
class CustomerAction extends CommonAction {
	//过滤查询字段
	private $position;
	private $rank;
	private $dept;

	public function _initialize() {
		parent::_initialize();
		$this -> position = M("Position") -> getField('id,name');
		$this -> rank = M("Rank") -> getField('id,name');
		$this -> dept = M("Dept") -> getField('id,name');
	}

	function _filter(&$map) {
                if($_POST['name']){$map['c.name'] = array('like', "%" . $_POST['name'] . "%");}
                if($_POST['letter']){$map['c.letter'] = array('like', "%" . $_POST['letter'] . "%");}
		//$map['status'] = array('eq', '1');
		if (!empty($_POST['group'])) {
			$map['c.group'] = $_POST['group'];
		}
		//$map['status'] = array('eq', '1');
		//$map['user_id'] = array('eq', $this -> get_user_id());
	}

	function index() {
		$model = M("Customer");
		//$where['user_id'] = array('eq', $this ->get_user_id());
                
                import('ORG.Util.Page');

                $children_depts = session('children_depts');

                $rank_id = session('rank_id');
                $user_id = session('authId');
                $where = "c.user_id = u.id and u.dept_id=d.id  and u.dept_id in ($children_depts) ";
                if($rank_id == 5){//级别为普通员工时
                    $where .=" and c.user_id = $user_id ";
                }else{
                    $where .=" and u.rank_id >= $rank_id ";
                }
                $count      = $model->table('think_user u,think_customer c,think_dept d')->where($where)->count();
                $this-> _config['list_rows'] = 2;//一页展示记录数
                $Page       = new Page($count,$this-> _config['list_rows']);// 实例化分页类 传入总记录数
                $show       = $Page->show();// 分页显示输出
                $list = $model->table('think_user u,think_customer c,think_dept d')->where($where)->limit($Page->firstRow.','.$Page->listRows)-> field('c.name,c.salesman,c.contact,c.office_tel,c.id,u.rank_id,u.dept_id,c.user_id') -> select();
                $this->assign('page',$show);// 赋值分页输出
                $this -> assign('list', $list);
                
                
		$group_data = D("Class") -> get_data_list("customer");
		$new = array();
		foreach ($group_data as $val) {
			$new[$val['obj_id']] = $new[$val['obj_id']] . $val['class_id'] . ",";
		}
		$this -> assign('group_data', $new);
		$this -> group_list();
                

		$this -> display();
		return;
	}

	function export() {
		$model = M("Customer");
		$where['user_id'] = array('eq', $this -> get_user_id());
		$list = $model -> where($where) -> select();

		Vendor('Excel.PHPExcel');
		//导入thinkphp第三方类库

		$inputFileName = C("SAVE_PATH") . "templete/Customer.xlsx";
		$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);

		$objPHPExcel -> getProperties() -> setCreator("小薇") -> setLastModifiedBy("小薇") -> setTitle("Office 2007 XLSX Test Document") -> setSubject("Office 2007 XLSX Test Document") -> setDescription("Test document for Office 2007 XLSX, generated using PHP classes.") -> setKeywords("office 2007 openxml php") -> setCategory("Test result file");
		// Add some data
		$i = 1;
		//dump($list);
		foreach ($list as $val) {
			$i++;
			$objPHPExcel -> setActiveSheetIndex(0) -> setCellValue("A$i", $val["name"]) -> setCellValue("B$i", $val["company"]) -> setCellValue("C$i", $val["dept"]) -> setCellValue("D$i", $val["position"]) -> setCellValue("E$i", $val["office_tel"]) -> setCellValue("F$i", $val["mobile_tel"]) -> setCellValue("G$i", $val["email"]) -> setCellValue("H$i", $val["im"]) -> setCellValue("I$i", $val["website"]) -> setCellValue("J$i", $val["address"]) -> setCellValue("J$i", $val["remark"]);
		}
		// Rename worksheet
		$objPHPExcel -> getActiveSheet() -> setTitle('Customer');

		// Set active sheet index to the first sheet, so Excel opens this as the first sheet
		$objPHPExcel -> setActiveSheetIndex(0);

		// Redirect output to a client’s web browser (Excel2007)
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="' . $file_name . '"');
		header('Cache-Control: max-age=0');

		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		$objWriter -> save('php://output');
		exit ;
	}

	public function import() {
		$save_path = C('SAVE_PATH');
		$opmode = $_POST["opmode"];
		if ($opmode == "import") {
			import("@.ORG.Util.UploadFile");
			$upload = new UploadFile();
			$upload -> savePath = $save_path;
			$upload -> allowExts = array('xlsx');
			$upload -> saveRule = uniqid;
			$upload -> autoSub = false;

			if (!$upload -> upload()) {
				$this -> error($upload -> getErrorMsg());
			} else {
				//取得成功上传的文件信息
				$uploadList = $upload -> getUploadFileInfo();
				Vendor('Excel.PHPExcel');
				//导入thinkphp第三方类库

				$inputFileName = $save_path . $uploadList[0]["savename"];
				$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
				$sheetData = $objPHPExcel -> getActiveSheet() -> toArray(null, true, true, true);
				$model = M("Customer");
				for ($i = 2; $i <= count($sheetData); $i++) {
					$data = array();
					$data['name'] = $sheetData[$i]["A"];
					$data['company'] = $sheetData[$i]["B"];
					$data['letter'] = get_letter($sheetData[$i]["A"]);
					$data['dept'] = $sheetData[$i]["C"];
					$data['position'] = $sheetData[$i]["D"];
					$data['email'] = $sheetData[$i]["G"];
					$data['office_tel'] = $sheetData[$i]["E"];
					$data['mobile_tel'] = $sheetData[$i]["F"];
					$data['website'] = $sheetData[$i]["I"];
					$data['im'] = $sheetData[$i]["H"];
					$data['address'] = $sheetData[$i]["J"];
					$data['user_id'] = $this -> get_user_id();
					$data['remark'] = $sheetData[$i]["K"];
					$data['status'] = 1;
					$model -> add($data);
				}
				//dump($sheetData);
				if (file_exists($_SERVER["DOCUMENT_ROOT"] . "/" . $inputFileName)) {
					unlink($_SERVER["DOCUMENT_ROOT"] . "/" . $inputFileName);
				}
				$this -> assign('jumpUrl', $this -> get_return_url());
				$this -> success('导入成功！');
			}
		} else {
			$this -> display();
		}
	}

	public function _conv_data(&$item) {
		if (isset($item['position_id'])) {
			$item['position_name'] = $this -> position[$item['position_id']];
		}
		if (isset($item['rank_id'])) {
			$item['rank_name'] = $this -> rank[$item['position_id']];
		}
		if (isset($item['dept_id'])) {
			$item['dept_name'] = $this -> dept[$item['dept_id']];
		}
		return $item;
	}

	public function _conv_list($list) {
		$list = array_map(array(__CLASS__, '_conv_data'), $list);
		return $list;
	}

	function mark() {
		$id = $_REQUEST["id"];
		$val = $_REQUEST["val"];
		$field = 'group';
		$result=$this -> set_field($id, $field, $val);
		if ($result !== false) {
			$this -> assign('jumpUrl', $this -> get_return_url());
			$this -> success('操作成功!');
		} else {
			//失败提示
			$this -> error('操作失败!');
		}		
	}

	function group_list() {
		$model = D("Class");
		$group_list = $model -> get_list('Customer', 'id,name', 'public');
		$this -> assign("group_list", $group_list);
	}

	function insert() {
		$ajax = $_POST['ajax'];
		$model = D('Customer');
		if (false === $model -> create()) {
			$this -> error($model -> getError());
		}
		$model -> __set('letter', get_letter($model -> __get('name')));
                if($_POST['user_id']){
                    $user_id = $_POST['user_id'];
                    $dept_id = $_POST['dept_id'];
                }else{
                   $salesman =  session('user_name');
                   $model -> __set('salesman',  $salesman);
                   $user_id = $this -> get_user_id();
                   $dept_id = session('dept_id');
                }
                $model -> __set('addtime', time());
		$model -> __set('user_id', $user_id);
                $model -> __set('dept_id', $dept_id);
		//保存当前数据对象
		$list = $model -> add();
		if ($list !== false) {//保存成功
			if ($ajax || $this -> isAjax())
				$this -> ajaxReturn($list, "新增成功", 1);
			$this -> assign('jumpUrl', $this -> get_return_url());
			$this -> success('新增成功!');
		} else {
			//失败提示
			$this -> error('新增失败!');
		}
	}

	function update() {
		$ajax = $_POST['ajax'];
		$id = $_POST['id'];
		$model = D("Customer");
		if (false === $model -> create()) {
			$this -> error($model -> getError());
		}
		$model -> __set('letter', get_letter($model -> __get('name')));
		// 更新数据
		$list = $model -> save();
		if (false !== $list) {
			//成功提示
			//$this -> assign('jumpUrl', $this -> get_return_url());
                        if($ajax == 1){
			$this -> success('编辑成功!');
                        }else{
                        $this -> assign('jumpUrl', $this -> get_return_url());
                        }
		} else {
			//错误提示
			$this -> error('编辑失败!');
		}
	}
        
	public function password() {
		$this -> assign("id", $_REQUEST['id']);
		$this -> display();
	}
        
        	public function reset_pwd() {
		$id = $_POST['id'];
		$password = $_POST['password'];
		if ('' == trim($password)) {
			$this -> error('密码不能为空！');
		}
		$User = M('Customer');
		$User -> password = md5($password);
		$User -> id = $id;
		$result = $User -> save();
		if (false !== $result) {
			//$this -> assign('jumpUrl', $this -> get_return_url());
		$this -> ajaxReturn($result, "密码修改成功", 1);	
		} else {
			$this -> error('重置密码失败！');
		}
	}
        
	function del() {
		if (!empty($_POST['customer_id'])) {
			$model = M("Customer");
			$Customer_list = $_POST['customer_id'];
			if (!is_array($Customer_list)) {
				$Customer_list = explode(",", $Customer_list);
			}
			$where['id'] = array('in', $Customer_list);
			$where['user_id'] = $this -> get_user_id();
			$model -> where($where) -> delete();
			$model = D("Class");
			$result = $model -> del_data_by_obj($_POST['customer_id'], 'Customer');
		};
		if ($result !== false) {//保存成功
			if ($ajax || $this -> isAjax())
				$this -> ajaxReturn($list, "操作成功", 1);
			$this -> assign('jumpUrl', $_POST['return_url']);
			$this -> success('操作成功!');
		} else {
			//失败提示
			$this -> error('操作失败!');
		}
	}

            
        function info(){
                        $model = M('Customer');
			$id = $this -> get_user_id();
			$vo = $model -> getById($id);
			$this -> assign('vo', $vo);
			$this -> display();
        }
        
	function read() {
		$type = $_REQUEST['type'];
		if ($type != 'inside') {
			$model = M('Customer');
			$id = $_REQUEST[$model -> getPk()];
			$vo = $model -> getById($id);
			$this -> assign('vo', $vo);
			$this -> display();
		} else {
			$User = D("User");
			$User -> viewFields = array('User' => array('id', 'status', 'nickname' => 'name'), 'Dept' => array('name' => 'dept', '_on' => 'User.dept_id =Dept.id', '_type' => 'LEFT'), 'UserInfo' => array('office_tel' => 'office_tel', 'mobile_tel' => 'mobile_tel', 'email' => 'email', 'website' => 'website', 'im' => 'im', '_on' => 'User.id=UserInfo.id'));
			$UserView = $User -> switchModel("View", array("viewFields"));
			$map['User.id'] = array('eq', $_REQUEST['id']);
			$vo = $UserView -> where($map) -> find();
			$this -> assign('accessList', $accessList);
			$this -> assign('vo', $vo);
			$this -> assign('actionName', $type);
			$this -> display('inside_read');
		}
	}

	function set_group() {
		if (!empty($_POST['customer_id'])) {
			$model = D("Class");
			$model -> del_data_by_obj($_POST['customer_id'], 'customer');
			if (!empty($_POST['group'])) {
				$result = $model -> set_class($_POST['customer_id'], $_POST['group'], "customer");
			}
		};
		if (!empty($_POST['new_group'])) {
			$model = M("Class");
			$model -> type = "customer";
			$model -> name = $_POST['new_group'];
			$model -> status = 1;
			$model -> user_id = $this -> get_user_id();
			$new_group_id = $model -> add();
			if (!empty($_POST['customer_id'])) {
				$model = D("Class");
				$result = $model -> set_class($_POST['customer_id'], $new_group_id, "customer");
			}
		};
		if ($result !== false) {//保存成功
			if ($ajax || $this -> isAjax())
				$this -> ajaxReturn($list, "操作成功", 1);
			$this -> assign('jumpUrl', $_POST['return_url']);
			$this -> success('操作成功!');
		} else {
			//失败提示
			$this -> error('操作失败!');
		}
	}

	function ajaxRead() {
		$type = $_REQUEST['type'];
		$id = $_REQUEST['id'];

		switch ($type) {
			case "company" :
				$model = M("Dept");
				$dept = tree_to_list(list_to_tree( M("Dept") -> select(), $id));
				$dept = rotate($dept);
				$dept = implode(",", $dept['id']) . ",$id";

			case "emp" :
				$model = M("Dept");
				$dept = tree_to_list(list_to_tree( M("Dept") -> select(), $id));
				$dept = rotate($dept);
				$dept = implode(",", $dept['id']) . ",$id";

				$model = M("User");
				$where['dept_id'] = array('in', $dept);
				$data = $model -> where($where) -> field('id,emp_no,emp_name,dept_id,email,position_id') -> select();
				break;
			case "rank" :
				$model = M("User");
				$where['rank_id'] = array('eq', $id);
				$data = $model -> where($where) -> field('id,emp_no,emp_name,email') -> select();
				break;

			case "position" :
				$model = M("User");
				$where['position_id'] = array('eq', $id);
				$data = $model -> where($where) -> field('id,emp_no,emp_name,email') -> select();
				break;

			case "personal" :
				$model = D("Class");
				if ($id == "#") {
					$data = $model -> get_data_list("Customer");
					$data = rotate($data);
					$data = $data['obj_id'];
					$where['id'] = array('not in', implode(",", $data));
				} else {
					$data = $model -> get_data_list("Customer", $id);
					$data = rotate($data);
					$data = $data['obj_id'];
					$where['id'] = array('in', implode(",", $data));
				}
				$model = M("Customer");
				$data = $model -> where($where) -> field('id,name emp_name,email') -> select();
				//echo $model->getLastSql();
				break;
			default :
		}
		$new = array();
		foreach ($data as $val) {
			$new[] = $this -> _conv_data($val);
		}
		if (true) {// 读取成功
			$this -> ajaxReturn($new, "", 1);
		}
	}

        
        public function select_customer(){
                 $model = M("Customer");
		//$where['user_id'] = array('eq', $this ->get_user_id());
                
                import('ORG.Util.Page');

                $map = $this -> _search();
		if (method_exists($this, '_filter')) {
			$this -> _filter($map);
		}
                
                $children_depts = session('children_depts');

                $rank_id = session('rank_id');
                $user_id = session('authId');
                $where = "c.user_id = u.id and u.dept_id=d.id  and u.dept_id in ($children_depts) ";
                if($rank_id == 5){//级别为普通员工时
                    $where .=" and c.user_id = $user_id ";
                }else{
                    $where .=" and u.rank_id >= $rank_id ";
                }
                $map['_string'] = $where;
                $count      = $model->table('think_user as u,think_customer as c,think_dept as d')->where($map)->count();
                $this-> _config['list_rows'] = 2;//一页展示记录数
                $Page       = new Page($count,$this-> _config['list_rows']);// 实例化分页类 传入总记录数
                $show       = $Page->show();// 分页显示输出
                $list = $model->table('think_user u,think_customer c,think_dept d')->where($map)->limit($Page->firstRow.','.$Page->listRows)-> field('c.name,c.salesman,c.contact,c.office_tel,c.mobile_tel,c.id,u.rank_id,u.dept_id,c.user_id') -> select();
                $this->assign('page',$show);// 赋值分页输出
                $this -> assign('list', $list);
                $this->display();
        }
        

}
?>